package dyyx.util;

import java.io.StringReader;
import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;

public class TransferUtil {

	private static final String DOT = ".";

	public static String yml2properties(String str) throws Exception {
		StringBuilder sb = new StringBuilder();

		YAMLFactory yamlFactory = new YAMLFactory();
		YAMLParser parser = yamlFactory.createParser(new StringReader(str));

		String key = "";
		String value = null;
		JsonToken token = parser.nextToken();
		while (token != null) {
			if (JsonToken.START_OBJECT.equals(token)) {
				// do nothing
			} else if (JsonToken.FIELD_NAME.equals(token)) {
				if (key.length() > 0) {
					key = key + DOT;
				}
				key = key + parser.getCurrentName();

				token = parser.nextToken();
				if (JsonToken.START_OBJECT.equals(token)) {
					continue;
				}
				value = parser.getText();
				sb.append(key + "=" + value).append("\n");

				int dotOffset = key.lastIndexOf(DOT);
				if (dotOffset > 0) {
					key = key.substring(0, dotOffset);
				}
				value = null;
			} else if (JsonToken.END_OBJECT.equals(token)) {
				int dotOffset = key.lastIndexOf(DOT);
				if (dotOffset > 0) {
					key = key.substring(0, dotOffset);
				} else {
					// key = "";
					// sb.append(key + "=" + value).append("\n");
				}
			}
			token = parser.nextToken();
		}
		parser.close();

		return sb.toString();
	}

	public static String properties2yaml(String str) throws Exception {
		JsonParser parser = null;
		JavaPropsFactory factory = new JavaPropsFactory();

		parser = factory.createParser(new StringReader(str));
		
		
		StringWriter writer = new StringWriter();
		YAMLFactory yamlFactory = new YAMLFactory();
		YAMLGenerator generator = yamlFactory.createGenerator(writer);

		JsonToken token = parser.nextToken();

		while (token != null) {
			if (JsonToken.START_OBJECT.equals(token)) {
				generator.writeStartObject();
			} else if (JsonToken.FIELD_NAME.equals(token)) {
				generator.writeFieldName(parser.getCurrentName());
			} else if (JsonToken.VALUE_STRING.equals(token)) {
				generator.writeString(parser.getText());
			} else if (JsonToken.END_OBJECT.equals(token)) {
				generator.writeEndObject();
			}
			token = parser.nextToken();
		}
		generator.flush();
		// writer.flush();
		String result = writer.toString();
		
		parser.close();
		generator.close();

		return result;

	}

}
